package com.itlong.cloud.rabbitmq.consumer;

import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.app.service.IAppCloudElevatorCallStatusService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      更新APP用户呼梯预约状态消费者
 * </desc>
 *
 * @createDate 2018/04/12
 */
@Component
public class CallElevatorOperateStatusConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(CallElevatorOperateStatusConsumer.class);

    @Autowired
    IAppCloudElevatorCallStatusService iAppCloudElevatorCallStatusService;


    /**
     * <desc>
     *      接收电梯实时上报状态消息，并更新用户呼梯行程状态
     * <desc/>
     *
     * @param   message 消息数据
     * @author Jiaqi.X
     * @createDate 2018/04/13
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_CALL_ELEVATOR_OPERATE_STATUS_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        try {
            TimeTaskDeadMessageQueuePO po= JsonUtil.toObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            Map<String,Object> map=JsonUtil.toObject(po.getMessageContent(),HashMap.class);
            IotCloudElevatorStateDTO dto = JsonUtil.toObject(map.get("data").toString(), IotCloudElevatorStateDTO.class);
            //更新用户云电梯预约状态
            iAppCloudElevatorCallStatusService.updateCallStatus(dto);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            throw new DataAccessException("【RabbitMQ_更新用户呼梯行程状态】:处理异常"+new String(body), e);
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}